package com.littlebee.storychild.ui;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.littlebee.storychild.R;
import com.zss.library.photopicker.utils.PhotoUtils;

/**
 * * @author 作者 : 落苏
 * 
 * @date 创建时间：2016年9月26日 下午4:03:47
 */

public class customCamer extends Activity implements SurfaceHolder.Callback {
	private Camera mCamera;
	/**
	 * 用于预览相机的效果
	 */
	private SurfaceView surfaceview;
	private SurfaceHolder holder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera);
		surfaceview = (SurfaceView) findViewById(R.id.surfaceview);
		holder = surfaceview.getHolder();
		holder.addCallback(this);
		surfaceview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mCamera.autoFocus(null);

			}
		});
	}

	public void capture(View view) {
		Camera.Parameters parameters = mCamera.getParameters();
		parameters.setPictureFormat(ImageFormat.JPEG);
		parameters.setPictureSize(800, 400);
		parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
	
		//自动对焦
		mCamera.autoFocus(new AutoFocusCallback() {

			@Override
			public void onAutoFocus(boolean success, Camera camera) {
				// TODO Auto-generated method stub
				if (success) {
					mCamera.takePicture(null, null, new PictureCallback() {

						@Override
						public void onPictureTaken(byte[] data, Camera camera) {
							Bitmap bMap;
							try
							{// 获得图片
								bMap = BitmapFactory.decodeByteArray(data, 0, data.length);

								Bitmap bMapRotate;
									Matrix matrix = new Matrix();
									matrix.reset();
									matrix.postRotate(-90);//旋转-90度
									bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(),
											bMap.getHeight(), matrix, true);
									bMap = bMapRotate;
								//}

								// Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
								File tempFile = PhotoUtils.createFile(getApplicationContext());
								BufferedOutputStream bos =
										new BufferedOutputStream(new FileOutputStream(tempFile));
								bMap.compress(Bitmap.CompressFormat.JPEG, 60, bos);//将图片压缩到流中
								bos.flush();//输出
								bos.close();//关闭
								Intent intent = new Intent();

								intent.putExtra("date", tempFile.getAbsolutePath());
								setResult(Activity.RESULT_OK, intent);
								customCamer.this.finish();
							}catch(Exception e)
							{
								e.printStackTrace();
							}

						}




//						// TODO Auto-generated method stub
//							File tempFile;/** = new File("/sdcard/tempforself.png");*/
//							tempFile = PhotoUtils.createFile(getApplicationContext());
//
//							FileOutputStream fos;
//							try {
//								//拍摄后照片后的结果处理
//								fos = new FileOutputStream(tempFile);
//								fos.write(data);
//								fos.close();
////								Intent intent = new Intent(customCamer.this, MainActivity.class);
////								intent.putExtra("picPath", tempFile.getAbsolutePath());
////								startActivity(intent);
//
//								Intent intent = new Intent();
//
//								intent.putExtra("date", tempFile.getAbsolutePath());
//								setResult(Activity.RESULT_OK, intent);
//								customCamer.this.finish();
//
//							} catch (FileNotFoundException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							} catch (IOException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//						}
					});

				} else {
					Toast.makeText(getApplicationContext(), "拍摄失败", Toast.LENGTH_SHORT).show();
				}

			}
		});
	}

	private Camera getCamera() {
		Camera camera = null;
		//调用前置摄像头的代码；
		//如果想后置摄像头，可直接Camera.open();默认就是后置的
		Camera.CameraInfo info= new Camera.CameraInfo();
		int count= Camera.getNumberOfCameras();
		for (int i = 0; i < count; i++) {
			Camera.getCameraInfo(i, info);
			if (info.facing==Camera.CameraInfo.CAMERA_FACING_FRONT) {
				try {
					
				//打开前置相机
				camera = Camera.open(i);
				
				} catch (RuntimeException e) {
					// TODO: handle exception
				}
			}
			
		}
		
		return camera;
	}

	/**
	 * 开始预览相机内容
	 */
	private void setStartPreview(Camera camera, SurfaceHolder holder) {
		try {
			camera.setPreviewDisplay(holder);
			// 旋转90度，防止横屏
			camera.setDisplayOrientation(90);
			camera.startPreview();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 释放资源
	 */
	private void releaseCamera() {

		if (mCamera != null) {
			mCamera.setPreviewCallback(null);
			mCamera.stopPreview();

			mCamera.release();
			mCamera = null;

		}
	}

	@Override
	protected void onResume() {
		if (mCamera == null) {
			mCamera = getCamera();
			if (holder != null) {
				setStartPreview(mCamera, holder);
			}

		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		releaseCamera();
		super.onPause();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		setStartPreview(mCamera, customCamer.this.holder);

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		// TODO Auto-generated method stub
		mCamera.stopPreview();
		setStartPreview(mCamera, customCamer.this.holder);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		releaseCamera();

	}

}
